<template>
	<view v-if="carts.length > 0">
		<view class="address u-p-30 u-flex u-row-between">
			<view class="left">
				<view class="add">{{add}}</view>
				<view class="phone">{{phone}}</view>
			</view>
			<view class="right" @tap="jump('pages/cart/add')">
				<u-icon name="arrow-right" color="#999" size="28"></u-icon>
			</view>
		</view>
		<view class="carts-wrapper">
			<!-- carts 组件 -->
			<carts :carts="carts"></carts>

			<view class="cartBtn u-p-30 u-flex u-row-between">
				<view class="total u-m-r-40 u-col u-flex-1">
					合计 {{totalNum}} 元
				</view>
				<u-button type="error" size="medium" @click="pay">提交订单并支付</u-button>
			</view>
		</view>

		<u-popup v-model="show" mode="center" @close="closePopup">
			<u-image width="300rpx" height="300rpx" :src="qr_code_url"></u-image>
		</u-popup>
	</view>
	<view v-else class="u-flex u-row-center u-col-center u-direction-row" style="height: 60vh;">
		<u-empty text="数据为空"></u-empty>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				add: '',
				phone: '',
				carts: [],
				address_id: '',
				show: false,
				qr_code_url: '',
				timer: null
			}
		},
		computed: {
			totalNum() {
				return this.carts.reduce((pre, cur) => {
					return parseInt(pre + (cur.num * cur.goods.price))
				}, 0)
			}
		},
		onLoad() {
			this.getViewCart()
		},
		methods: {
			async getViewCart() {
				const res = await this.$u.api.viewCart()
				this.getData(res);
			},
			getData(res) {
				console.log(res)
				res.address.map(e => {
					if (e.is_default) {
						this.add = e.city + e.county + e.address
						this.phone = e.name + e.phone
						this.address_id = e.id
					}
				})
				this.carts = res.carts
			},
			/**
			 * 跳转页面
			 */
			jump(url) {
				this.$u.route(url)
			},

			/**
			 * 监听支付状态
			 */
			payStu(id) {
				let payStu = '';
				clearInterval(this.timer);
				this.timer = setInterval(async () => {
					payStu = await this.$u.api.payStatus(id);
					// 支付成功
					if (payStu === '2') {
						this.show = false;
						clearInterval(this.timer)
					}
					console.log('监听支付状态', payStu)
				}, 1000);
			},
			/**
			 * 支付并提交
			 */
			async pay() {
				const params = {
					address_id: this.address_id
				}
				console.log(this.address_id, params)
				const res = await this.$u.api.subCart(params)
				const id = parseInt(res.id);
				console.log(id)
				const data = await this.$u.api.pay(id, {
					type: 'aliyun'
				});
				console.log(data);
				if (data.msg === 'Success') {
					this.show = true
					this.qr_code_url = data.qr_code_url;
					this.payStu(id);
				}
			},
			closePopup() {
				clearInterval(this.timer)
			}
		}
	}
</script>

<style lang="scss" scoped>
	.address {
		border-bottom: 1px solid #eee;
	}

	.total {
		color: $u-type-error;
		font-weight: bold;
	}
</style>
